import { FormOutlined, MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { Button, Input } from 'antd';
import { cloneDeep } from 'lodash';
import { nanoid } from 'nanoid';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import './index.less';
const GeneralCon: React.FC<any> = forwardRef((props: any, ref) => {
  const { loading, isBottomForm = false, data, setBottomForm, updataPoints } = props;
  const { TextArea } = Input;
  const [disabled, setDisabled] = useState<boolean>(true);
  const [edit, setEdit] = useState(false);
  const [pointsList, setPointsList] = useState<any>([]); //要点列表
  const [labelStyle, setLabelStyle] = useState({}); //label的宽度 根据标题长度计算 一个字符15px

  //动态计算labelWidth的宽度
  const computeLabelWidth = () => {
    let lWidth = 0;
    data.forEach(async (item: any) => {
      const titleLength = item.title.length || 1;
      const addWidth = item.can_add === 1 && edit ? 30 : 0; //添加图标的宽度
      if (titleLength * 18 > lWidth) {
        lWidth = titleLength * 18 + addWidth;
      }
    });
    setLabelStyle({
      width: `${lWidth}px`,
    });
  };

  //外部传入data时 初始化
  useEffect(() => {
    if (data) {
      let anchorObj = data?.find((item: any) => item.is_list === 1);
      const titleWithoutNumber = anchorObj?.title?.replace(/\d+/g, '');
      data.forEach(async (item: any) => {
        if (anchorObj && item.title === anchorObj.title) {
          item.anchor = true;
          item.anchorName = titleWithoutNumber;
        } else if (anchorObj) {
          item.anchor = false;
          item.anchorName = titleWithoutNumber;
        }
      });
      setPointsList(data);
      computeLabelWidth();
    }
  }, [data]);

  //如果是isBottomForm的话 开启编辑模式
  useEffect(() => {
    if (isBottomForm) {
      setEdit(true);
      setDisabled(false);
    }
  }, []);

  useEffect(() => {
    computeLabelWidth();
  }, [edit]);
  //编辑 | 取消
  const editAglin = (edit: boolean) => {
    setEdit(edit);
    setDisabled(!edit);
    computeLabelWidth();
  };

  const general = () => {
    updataPoints(pointsList);
    setEdit(false);
    setDisabled(true);
  };
  //输入框修改
  const handleChangeParaEdit = (index: number, e: any) => {
    pointsList[index].content = e.target.value || '';
  };
  //添加一行
  const addItem = (index: number) => {
    const pointsCopy: any = cloneDeep(pointsList);
    const item = pointsCopy[index];
    const item_new = {
      key: nanoid(),
      title: item.title,
      content: '',
      can_add: item.can_add,
    };
    pointsCopy.splice(index + 1, 0, item_new);
    setPointsList(pointsCopy);
    //如果是底部表单的数据 那么将数据setBottomForm 回显到上级页面
    if (isBottomForm) {
      setBottomForm(pointsCopy);
    }
  };
  //添加一行
  const addItem2 = (index: number) => {
    const pointsCopy: any = cloneDeep(pointsList);
    const item = pointsCopy[index];
    const item_new: any = {
      ...item,
      key: nanoid(),
      title: item.title,
      content: '',
      can_add: item.can_add,
      anchor: false,
    };
    delete item_new.is_list; //删除+按钮表示字段
    pointsCopy.push(item_new);
    //重新计算索引
    let idx = 1;
    pointsCopy.forEach((ele: any) => {
      if (ele?.title?.indexOf(ele?.anchorName) >= 0) {
        ele.title = ele.anchorName + idx;
        idx++;
      }
    });
    setPointsList(pointsCopy);
    //如果是底部表单的数据 那么将数据setBottomForm 回显到上级页面
    if (isBottomForm) {
      setBottomForm(pointsCopy);
    }
  };
  const removeItem2 = (index: number) => {
    const pointsCopy: any = cloneDeep(pointsList);
    pointsCopy.splice(index, 1);
    //重新计算索引
    let idx = 1;
    pointsCopy.forEach((ele: any) => {
      if (ele?.title?.indexOf(ele?.anchorName) >= 0) {
        ele.title = ele.anchorName + idx;
        idx++;
      }
    });
    setPointsList(pointsCopy);
  };

  //placeholder 文案
  const handlePlaceholder = (item: any) => {
    if (isBottomForm) {
      return `请输入...${item.background_info}`;
    } else {
      return `补充该信息文章会生成的更好`;
    }
  };
  //取消编辑 数据重置
  const cancelEdit = () => {
    let anchorObj = data?.find((item: any) => item.is_list === 1);
    const titleWithoutNumber = anchorObj?.title?.replace(/\d+/g, '');
    data.forEach(async (item: any) => {
      if (anchorObj && item.title === anchorObj.title) {
        item.anchor = true;
        item.anchorName = titleWithoutNumber;
      } else if (anchorObj) {
        item.anchor = false;
        item.anchorName = titleWithoutNumber;
      }
    });
    setPointsList(data);
    computeLabelWidth();
    editAglin(false);
  };
  const getPoints = () => {
    return {
      edit: edit,
      pointsList: pointsList,
    };
  };
  useImperativeHandle(ref, () => ({
    getPoints,
  }));

  return (
    <div ref={ref} className={isBottomForm ? 'gen-content bottom-form' : 'gen-content'}>
      {/* 底部的表单不显示编辑按钮 */}
      {!isBottomForm ? (
        <div className="title">
          <div className="">{!loading ? '请确认关键信息是否准确，可以点击【编辑】修改' : ''}</div>
          {!loading && (
            <div className="edit">
              {!edit ? (
                <div
                  onClick={() => editAglin(true)}
                  style={{ color: '#3E4352', cursor: 'pointer' }}
                >
                  <FormOutlined style={{ marginRight: '6px' }} />
                  编辑
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'row', color: '#979797' }}>
                  <div
                    onClick={() => cancelEdit()}
                    className=""
                    style={{
                      color: '#3E4352',
                      opacity: '0.7',
                      cursor: 'pointer',
                      padding: '0 10px',
                    }}
                  >
                    取消
                  </div>{' '}
                  |
                  <div
                    onClick={general}
                    className=""
                    style={{ color: '#397BFF', cursor: 'pointer', paddingLeft: '10px' }}
                  >
                    确定
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      ) : (
        <></>
      )}
      {pointsList.length > 0 &&
        pointsList.map((item: any, index: number) => {
          return (
            <div className="genral-list" key={item.key}>
              <div className={`genral-list-hd ${!edit ? 'vamiddle' : ''}`} style={labelStyle}>
                {item.title}:
                {item.can_add === 1 && edit && (
                  <Button
                    type="text"
                    size="small"
                    shape="circle"
                    icon={<PlusCircleOutlined />}
                    onClick={() => addItem(index)}
                  />
                )}
                {item.can_add === -1 && edit && (
                  <Button
                    type="text"
                    size="small"
                    shape="circle"
                    icon={<PlusCircleOutlined />}
                    onClick={() => addItem(index)}
                  />
                )}
                {item.anchor && edit && (
                  <Button
                    type="text"
                    size="small"
                    shape="circle"
                    icon={<PlusCircleOutlined />}
                    onClick={() => addItem2(index)}
                  />
                )}
                {!item.anchor && item?.title.indexOf(item?.anchorName) >= 0 && edit && (
                  <Button
                    type="text"
                    size="small"
                    shape="circle"
                    icon={<MinusCircleOutlined />}
                    onClick={() => removeItem2(index)}
                  />
                )}
              </div>
              <div className="genral-list-bd">
                {/* <TextArea
                    autoSize={{ maxRows: 3 }}
                    bordered={!edit}
                    defaultValue={item.content}
                    onChange={(e) => handleChangeParaEdit(index, e)}
                ></TextArea> */}
                <TextArea
                  placeholder={handlePlaceholder(item)}
                  bordered={!disabled}
                  disabled={disabled}
                  autoSize={{ maxRows: 50, minRows: pointsList.length === 1 ? 4 : 1 }}
                  defaultValue={item.content}
                  onChange={(e) => handleChangeParaEdit(index, e)}
                ></TextArea>
              </div>
            </div>
          );
        })}
    </div>
  );
});

export default GeneralCon;
